package com.zmx.piglearn.utils

import android.content.Context
import android.content.ContextWrapper
import android.os.Environment
import android.widget.Toast
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.lang.StringBuilder

class SDFileHelper(private val context: Context) {
    fun save(filename: String, content: String) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            val filePath = ContextWrapper(context).getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            val file = File(filePath, filename)
            val output = FileOutputStream(file)
            output.write(content.toByteArray())
            output.close()
        } else {
            Toast.makeText(context, "SD 卡不存在或不可读写", Toast.LENGTH_SHORT).show()
        }
    }

    fun read(filename: String): String {
        val sb = StringBuilder()
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            val filePath = ContextWrapper(context).getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)
            val file = File(filePath, filename)
            val input = FileInputStream(file)
            val buf = ByteArray(1024)
            var len = input.read(buf)
            while (len > 0) {
                sb.append(String(buf, 0, len))
                len = input.read(buf)
            }
            input.close()
        }
        return sb.toString()
    }
}